package com.hanhanxiaochong.zhongxiangchuanmei.view.main.act;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.hanhanxiaochong.zhongxiangchuanmei.R;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.ChooseCityModel;
import com.hanhanxiaochong.zhongxiangchuanmei.presenter.ChooseCityPresenter;
import com.hanhanxiaochong.zhongxiangchuanmei.util.MessageEvent;
import com.hanhanxiaochong.zhongxiangchuanmei.util.ResourcesUtils;
import com.hanhanxiaochong.zhongxiangchuanmei.util.city.CharacterParser;
import com.hanhanxiaochong.zhongxiangchuanmei.util.city.CitySortModel;
import com.hanhanxiaochong.zhongxiangchuanmei.util.city.PinyinComparator;
import com.hanhanxiaochong.zhongxiangchuanmei.util.city.SortAdapter;
import com.hanhanxiaochong.zhongxiangchuanmei.view.base.BaseActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.iview.IChooseCityView;
import com.hanhanxiaochong.zhongxiangchuanmei.widget.SideBar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * 城市列表
 */
public class ChooseCityActivity extends BaseActivity<ChooseCityPresenter> implements IChooseCityView, AMapLocationListener {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.choose_city_listview)
    ListView chooseCityListview;
    @BindView(R.id.choose_city_dialog)
    TextView chooseCityDialog;
    @BindView(R.id.choose_city_sidrbar)
    SideBar sideBar;

    private ArrayList<ChooseCityModel.ListBean> list;
    private CharacterParser characterParser;
    private SortAdapter adapter;
    private List<CitySortModel> sourceDateList;
    private List<CitySortModel> searchLiset = new ArrayList<>();
    //当前列表展示的数据,0所有城市,1搜索结果
    private int listStatus;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    private TextView currentCity;

    public static Intent createIntent(Context context){
        return new Intent(context,ChooseCityActivity.class);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_choose_city);
    }

    @Override
    protected void initPresenter() {
        mPresenter = new ChooseCityPresenter(this);
    }

    @Override
    protected void init() {
        initLocation();
        mPresenter.getCityData();
        chooseCityListview.addHeaderView(initHeadView());
        characterParser = CharacterParser.getInstance();
        sideBar.setTextView(chooseCityDialog);
        sideBar.setOnTouchingLetterChangedListener(s -> {
            int position = adapter.getPositionForSection(s.charAt(0));
            if (position != -1) {
                chooseCityListview.setSelection(position + 1);
            }
        });

        chooseCityListview.setOnItemClickListener((parent, view, position, id) -> {
            MessageEvent messageEvent = new MessageEvent(sourceDateList.get(position - 1).getName());
            messageEvent.setFrom("city");
            EventBus.getDefault().post(messageEvent);
            finish();
        });

        etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String keyword = etSearch.getText().toString().trim();
                for (int i = 0; i < sourceDateList.size(); i++) {
                    CitySortModel sortModel = sourceDateList.get(i);
                    if (keyword.equals(sortModel.getCy_l_letter()) || keyword.equals(sortModel.getCy_letter()) ||
                            sortModel.getName().contains(keyword)) {
                        searchLiset.add(sortModel);
                    }
                }
                listStatus = 1;
                adapter.setDatas(searchLiset);
                 /*隐藏软键盘*/
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (inputMethodManager.isActive()) {
                    inputMethodManager.hideSoftInputFromWindow(ChooseCityActivity.this.getCurrentFocus().getWindowToken(), 0);
                }
            }
            return false;
        });
    }

    @Override
    public void setCityList(ChooseCityModel data) {
        if (list == null) {
            list = new ArrayList<>();
        }
        list.clear();
        if (data.getA() != null) {
            list.addAll(data.getA());
        }
        if (data.getB() != null) {
            list.addAll(data.getB());
        }
        if (data.getC() != null) {
            list.addAll(data.getC());
        }
        if (data.getD() != null) {
            list.addAll(data.getD());
        }
        if (data.getE() != null) {
            list.addAll(data.getE());
        }
        if (data.getF() != null) {
            list.addAll(data.getF());
        }
        if (data.getG() != null) {
            list.addAll(data.getG());
        }
        if (data.getH() != null) {
            list.addAll(data.getH());
        }
        if (data.getI() != null) {
            list.addAll(data.getI());
        }
        if (data.getJ() != null) {
            list.addAll(data.getJ());
        }
        if (data.getK() != null) {
            list.addAll(data.getK());
        }
        if (data.getL() != null) {
            list.addAll(data.getL());
        }
        if (data.getM() != null) {
            list.addAll(data.getM());
        }
        if (data.getN() != null) {
            list.addAll(data.getN());
        }
        if (data.getO() != null) {
            list.addAll(data.getO());
        }
        if (data.getP() != null) {
            list.addAll(data.getP());
        }
        if (data.getQ() != null) {
            list.addAll(data.getQ());
        }
        if (data.getR() != null) {
            list.addAll(data.getR());
        }
        if (data.getS() != null) {
            list.addAll(data.getS());
        }
        if (data.getT() != null) {
            list.addAll(data.getT());
        }
        if (data.getU() != null) {
            list.addAll(data.getU());
        }
        if (data.getV() != null) {
            list.addAll(data.getV());
        }
        if (data.getW() != null) {
            list.addAll(data.getW());
        }
        if (data.getX() != null) {
            list.addAll(data.getX());
        }
        if (data.getY() != null) {
            list.addAll(data.getY());
        }
        if (data.getZ() != null) {
            list.addAll(data.getZ());
        }

        sourceDateList = filledData(list);
        Collections.sort(sourceDateList, new PinyinComparator());
        adapter = new SortAdapter(this, sourceDateList);
        chooseCityListview.setAdapter(adapter);
    }

    private View initHeadView() {
        View header = ResourcesUtils.inflate(R.layout.header_city);
        currentCity = header.findViewById(R.id.tv_current_city);
        currentCity.setText("正在定位");
        header.setOnClickListener(v -> {
            MessageEvent messageEvent = new MessageEvent(currentCity.getText().toString());
            messageEvent.setFrom("city");
            EventBus.getDefault().post(messageEvent);
            finish();
        });
        return header;
    }

    @OnClick(R.id.iv_back)
    public void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }

    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        String city = aMapLocation.getCity();
        currentCity.setText(city);
    }

    private List<CitySortModel> filledData(List<ChooseCityModel.ListBean> list) {
        List<CitySortModel> mSortList = new ArrayList<>();
        ArrayList<String> indexString = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            ChooseCityModel.ListBean bean = list.get(i);
            CitySortModel sortModel = new CitySortModel();
            sortModel.setName(bean.getCy_name());
            sortModel.setCy_id(bean.getCy_id());
            sortModel.setCy_l_letter(bean.getCy_l_letter());
            sortModel.setCy_letter(bean.getCy_letter());
            sortModel.setCy_pid(bean.getCy_pid());
            String pinyin = characterParser.getSelling(sortModel.getName());
            String sortString = pinyin.substring(0, 1).toUpperCase();
            if (sortString.matches("[A-Z]")) {

                //对重庆多音字做特殊处理
                if (pinyin.startsWith("zhongqing")) {
                    sortString = "C";
                    sortModel.setSortLetters("C");
                } else {
                    sortModel.setSortLetters(sortString.toUpperCase());
                }

                if (!indexString.contains(sortString)) {
                    indexString.add(sortString);
                }
            }

            mSortList.add(sortModel);
        }
        Collections.sort(indexString);
        sideBar.setIndexText(indexString);
        return mSortList;
    }

    @Override
    public void onBackPressed() {
        if (listStatus == 0) {
            super.onBackPressed();
        } else {
            adapter.setDatas(sourceDateList);
        }
    }
}
